/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jus.aor.mobilagent.kernel;

import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;
import jus.aor.mobilagent.loader.BAMLoader;
import jus.aor.mobilagent.route.*;

/**
 *
 * @author thomas
 */
public abstract class AbstractAgent implements AgentInterface {

    protected Route route;
    private transient Jar classes;
    private transient AgentServerInterface agentServer;
    private transient String serverName;
    private transient BAMLoader loader;

    public AbstractAgent(Route route) {
        this.route = route;
    }

    @Override
    public void run() {
        Thread.currentThread().setContextClassLoader(loader);
        Etape e = route.next();
        String action = e.getAction();
//        System.out.println("Action: " + action);

        try {
            this.getClass().getMethod(action).invoke(this);
            
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
            Logger.getLogger(AbstractAgent.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (route.hasNext()) {
//            System.out.println(route);
            agentServer.sendAgentTo(this, route.get().getServer());
        }
    }

    @Override
    public void init(BAMLoader loader, AgentServerInterface agentServer, String serverName) {
        this.loader = loader;
        this.agentServer = agentServer;
        this.serverName = serverName;
    }

    @Override
    public void addEtape(Etape etape) {
        route.addEtape(etape);
    }

    @Override
    public void setClasses(Jar classes) {
        this.classes = classes;
    }

    @Override
    public Jar getClasses() {
        return classes;
    }

    @Override
    public void deploy() {
    }

    @Override
    public void finish() {
    }
}
